package models

import (
	"time"

	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type User struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	UID       string    `gorm:"uniqueIndex;size:16" json:"uid"`
	Name      string    `gorm:"uniqueIndex;not null" json:"name"`
	Phone     *string   `gorm:"size:20" json:"phone,omitempty"`
	Password  string    `gorm:"not null" json:"-"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// 关联
	Documents   []Document    `gorm:"foreignKey:UserID" json:"-"`
	TokenLogs   []ApiTokenLog `gorm:"foreignKey:UserID" json:"-"`
}

// BeforeCreate 钩子 - 生成 UID
func (u *User) BeforeCreate(tx *gorm.DB) error {
	if u.UID == "" {
		// 生成唯一的 uid
		for {
			uid := uuid.New().String()[:16]
			var existingUser User
			if err := tx.Where("uid = ?", uid).First(&existingUser).Error; err != nil {
				if err == gorm.ErrRecordNotFound {
					u.UID = uid
					break
				}
				return err
			}
		}
	}
	return nil
}

// HashPassword 加密密码
func (u *User) HashPassword(password string) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashedPassword)
	return nil
}

// CheckPassword 验证密码
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}